<?php

require_once('../const.php');

class DatabaseUtils{

	/**
	 * determines whether or not the database has been set up
	 * 
	 * @return boolean
	 */
	public static function databaseExists(){

		$db_connect = mysql_connect (DBHOST, DBUSERNAME, DBPASSWORD) or die ('I cannot connect to the database because: ' . mysql_error());
		$dbList = mysql_list_dbs($db_connect);

		if(!$dbList)
			return false;

		while ($row = mysql_fetch_array($dbList)) {
     		if ($row['Database'] == DBNAME)
     			return true; 
		}
		return false;
	}
	
	/**
	 * Creates the database if it doesn't already exists.
	 * Sets up the database tables.
	 * 
	 * @return boolean
	 */
	public static function createDatabase(){
		
		if(!self::databaseExists())
			$result = mysql_query("CREATE DATABASE " . DBNAME);

		self::createTables();
		header("Location: admincp.php");
		return $result;
	}

	/**
	 * loads the sql from an xml file to create the database
	 * tables.
	 * 
	 */
	private static function createTables(){

		mysql_select_db(DBNAME);
		$xml = simplexml_load_file("../tableschema.xml");

		foreach($xml->table as $table){
			$sql = str_replace("{CATEGORY_TABLE_NAME}", DB_CATEGORY_TABLE, $table->sql);
			$sql = str_replace("{POST_TABLE_NAME}", DB_POST_TABLE, $sql);
			mysql_query($sql);
		}
	}

	/**
	 * checks whether or not the table exists
	 * 
	 * @param String tableName
	 * @return boolean
	 */	
	public static function tableExists($tableName){
		
		$db_connect = mysql_connect (DBHOST, DBUSERNAME, DBPASSWORD) or die ('I cannot connect to the database because: ' . mysql_error());
		$tableList = mysql_query("SHOW TABLES FROM " . DBNAME);

		if(!$tableList)
			return false;
				
		while ($row = mysql_fetch_row($tableList)) {
     		if ($row[0] == $tableName)
     			return true; 
		}
		return false;
	}
}
?>
